package com.zsk.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class FileUtil {

	public static void emptyDir(String dirPath) {
		File file = new File(dirPath);
		if (!file.isDirectory()) {
			file.mkdirs();
			return;
		}
		File[] files = file.listFiles();
		for (File tmpFile : files)
			deleteFileOrFolder(tmpFile);

	}

	public static void makeDir(String dirPath) {
		File file = new File(dirPath);
		if (!file.isDirectory())
			file.mkdirs();
	}

	public static void deleteDir(String dir) {
		File dirFile = new File(dir);
		deleteFileOrFolder(dirFile);
	}

	/**
	 * Delete file directory
	 * 
	 * @param dir
	 */
	public static void deleteFileOrFolder(File file) {
		if (file == null || !file.exists() || !file.isDirectory())
			return;
		for (File f : file.listFiles()) {
			if (f.isFile())
				f.delete();
			else if (file.isDirectory())
				deleteFileOrFolder(f);
		}
		file.delete();
	}

	public static boolean writeTxtFile(String content, String filePath) {
		FileOutputStream fos = null;
		PrintWriter out = null;
		try {
			File dir = new File(filePath).getParentFile();
			if (!dir.isDirectory())
				dir.mkdirs();
			fos = new FileOutputStream(filePath);
			OutputStreamWriter rWriter = new OutputStreamWriter(fos, "utf-8");
			out = new PrintWriter(new BufferedWriter(rWriter));
			out.write(content);
			out.flush();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null)
					fos.close();
				if (out != null)
					out.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return false;

	}

	public static StringBuilder readTxtFile(String filePath) {
		StringBuilder sb = new StringBuilder();
		BufferedReader in = null;
		try {
			in = new BufferedReader(new FileReader(filePath));
			String str;
			while ((str = in.readLine()) != null) {
				sb.append(str + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb;
	}
}
